package com.qingcheng.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.qingcheng.service.goods.SkuSearchService;
import com.qingcheng.util.WebUtil;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.Map;

@Controller
public class SearchController {


    @Reference
    private SkuSearchService skuSearchService;

    @GetMapping("/search")
    public String search(Model model, @RequestParam Map<String,String> searchMap){
        //处理字符集
        try {
            searchMap = WebUtil.convertCharsetToUTF8(searchMap);
        } catch (Exception e) {
            e.printStackTrace();
        }

        //如果前台没有传页码参数,给个默认
        if (searchMap.get("pageNo")==null){
            searchMap.put("pageNo","1");
        }
        //如果没有进行排序查询
        if (searchMap.get("sort")==null){
            searchMap.put("sortOrder","DESC");
            searchMap.put("sort","");
        }


        //给前台返回当前的url
        StringBuffer url = new StringBuffer("/search.do?");
        for (String key : searchMap.keySet()) {
            url.append("&"+key+"="+searchMap.get(key));
        }
        model.addAttribute("url",url);
        //把传来的条件返回给前台
        model.addAttribute("searchMap",searchMap);




        //查询结果集
        Map result = skuSearchService.search(searchMap);
        model.addAttribute("result",result);


        int pageNo = Integer.parseInt(searchMap.get("pageNo"));
        model.addAttribute("pageNo",pageNo);

        //页码边界控制
        Long totalPage = (Long) result.get("totalPage");
        int startPage=pageNo-2;
        int endPage=pageNo+2;
        if (startPage<=0){
            startPage=1;
            endPage=5;
        }
        if (endPage>=totalPage){
            startPage=totalPage.intValue()-4;
            endPage=totalPage.intValue();
        }
        model.addAttribute("startPage",startPage);
        model.addAttribute("endPage",endPage);


        return "search";

    }
}
